package com.cjt.security;

import cn.hutool.json.JSONUtil;
import com.cjt.common.lang.R;
import com.cjt.utils.JwtUtils;
import com.cjt.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    JwtUtils jwtUtils;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream servletOutputStream = response.getOutputStream();

        //生成JWT 并设置到请求头中
        String jwt = jwtUtils.generateToken(authentication.getName());
        String header = jwtUtils.getHeader();

        String id = authentication.getName();


        response.setHeader(header,jwt);
        response.setHeader("username", id);
        //生成用户 姓名展示在请求头之中



        //TODO 并把jwt存进Redis中 并在 jwt拦截器中进行拦截判断 前端回传的jwt是否在redis中存在 没有即不合法
        redisUtil.set(id, jwt,604800);

        response.setHeader("Access-Control-Expose-Headers", header+",username");
        R r = R.success("");
        servletOutputStream.write(JSONUtil.toJsonStr(r).getBytes(StandardCharsets.UTF_8));

        servletOutputStream.flush();
        servletOutputStream.close();
    }
}
